<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
       <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="员工编号">
                  <a-input placeholder="系统自动生成" v-decorator="['empNo']" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="员工姓名">
                  <a-input placeholder="请输入员工姓名" v-decorator="['empName', validatorRules.empName]" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="手机号">
                  <a-input placeholder="请输入手机号" v-decorator="['phone', validatorRules.phone]" :disabled="disableSubmit" @change="handlePhoneChange"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="登录账号">
                  <a-tooltip>
                    <template slot="title">
                      登录账号必须为手机号码，默认使用联系手机号
                    </template>
                    <a-input placeholder="默认使用手机号" v-decorator="['username', validatorRules.username]" :disabled="model.id ? true : disableSubmit"/>
                  </a-tooltip>
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="登录密码">
                  <a-input type="password" placeholder="请输入登录密码" v-decorator="['password', validatorRules.password]" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="性别">
                  <j-dict-select-tag type="radio" v-decorator="['sex', validatorRules.sex]" :trigger-change="true" dictCode="sex" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="身份证号">
                  <a-input placeholder="请输入身份证号" v-decorator="['idCard', validatorRules.idCard]" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="出生日期">
                  <j-date
                    placeholder="请选择出生日期"
                    v-decorator="['birthday', validatorRules.birthday]"
                    :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="入职日期">
                  <j-date
                    placeholder="请选择入职日期"
                    v-decorator="['hireDate', validatorRules.hireDate]"
                    :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="工作状态">
                  <j-dict-select-tag v-decorator="['workStatus', validatorRules.workStatus]" :trigger-change="true" dictCode="work_status" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="所属部门">
                  <j-depart-tree-select
                    ref="departTreeSelect"
                    placeholder="请选择所属部门"
                    v-decorator="['departId', validatorRules.departId]"
                    :disabled="disableSubmit"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="职位">
                  <a-input placeholder="请输入职位" v-decorator="['positionName']" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="角色">
                  <j-select-role
                    placeholder="请选择角色"
                    v-decorator="['roleIds']"
                    :disabled="disableSubmit"
                    mode="multiple"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :labelCol="{span: 4}"
                  :wrapperCol="{span: 18}"
                  label="备注">
                  <a-textarea :rows="4" placeholder="请输入备注" v-decorator="['remark']" :disabled="disableSubmit"/>
                </a-form-item>
              </a-col>
            </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import JDepartTreeSelect from '@/components/jeecgbiz/JDepartTreeSelect'
  import JModal from '@/components/jeecg/JModal/JModal'
  import JDate from '@/components/jeecg/JDate'
  import JSelectRole from '@/components/jeecgbiz/JSelectRole'

  export default {
    name: "EmployeeModal",
    components: {
      JDictSelectTag,
      JTreeSelect,
      JDepartTreeSelect,
      JModal,
      JDate,
      JSelectRole
    },
    mounted() {
      console.log('EmployeeModal组件已挂载');
    },
    updated() {
      // 检查表单中的角色数据
      if (this.form && this.model.id) {
        const roleIds = this.form.getFieldValue('roleIds');
        if (roleIds) {
          console.log('表单角色数据类型:', typeof roleIds, Array.isArray(roleIds) ? '数组' : '非数组');
          console.log('表单角色数据:', roleIds);
        }
      }
    },
    data () {
      return {
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          empName: {rules: [{ required: true, message: '请输入员工姓名!' }]},
          sex: {rules: [{ required: true, message: '请选择性别!' }]},
          phone: {rules: [{ required: true, message: '请输入手机号!' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!' }]},
          idCard: {rules: [{ pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码!' }]},
          departId: {rules: [{ required: true, message: '请选择所属部门!' }]},
          workStatus: {rules: [{ required: true, message: '请选择工作状态!' }]},
          hireDate: {rules: [{ required: true, message: '请选择入职日期!' }]},
          username: {rules: [
            { required: true, message: '请输入登录账号!' }, 
            { pattern: /^1[3456789]\d{9}$/, message: '登录账号必须是有效的手机号码!' },
            { validator: this.validateUsername }
          ]},
          password: {rules: [{ required: function(form) {return !form.getFieldValue('id')}, message: '请输入登录密码!' }]}
        },
        url: {
          add: "/sys/employee/add",
          edit: "/sys/employee/edit",
          checkUsername: "/sys/employee/checkUsername",
          addEmployeeRole: "/sys/employeeRole/addEmployeeRole"
        },
        activeKey: "1",
        disableSubmit: false
      }
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.activeKey = "1";
        this.disableSubmit = false;
        
        console.log('编辑员工，员工ID:', this.model.id);
        
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'empNo','empName','sex','phone','idCard','departId','positionId','positionName','workStatus','remark','optimizeSoftType','username','password'))
          // 时间格式化
          this.form.setFieldsValue({
            birthday: this.model.birthday ? moment(this.model.birthday).format('YYYY-MM-DD') : null,
            hireDate: this.model.hireDate ? moment(this.model.hireDate).format('YYYY-MM-DD') : null
          })
          
          // 如果是编辑模式，获取员工的角色信息
          if (this.model.id) {
            console.log('开始加载角色信息，员工ID:', this.model.id);
            
            // 设置一个短暂延迟，确保表单完全初始化
            setTimeout(() => {
              this.loadEmployeeRoles(this.model.id).then(roleIds => {
                if (roleIds && roleIds.length > 0) {
                  console.log('角色信息加载完成，角色IDs:', roleIds);
                  // 设置角色信息 - 确保传入的是字符串
                  this.form.setFieldsValue({
                    roleIds: roleIds.join(',')
                  });
                }
              });
            }, 200);
          }
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            
            // 处理日期格式
            let formData = Object.assign(this.model, values);
            if(formData.birthday) {
              // 确保birthday是字符串
              formData.birthday = typeof formData.birthday === 'string' 
                ? formData.birthday 
                : moment(formData.birthday).format('YYYY-MM-DD');
            }
            if(formData.hireDate) {
              // 确保hireDate是字符串
              formData.hireDate = typeof formData.hireDate === 'string'
                ? formData.hireDate
                : moment(formData.hireDate).format('YYYY-MM-DD');
            }
            
            // 保存角色信息
            const roleIds = formData.roleIds;
            // 如果roleIds是字符串，转换为数组
            const roleIdArray = typeof roleIds === 'string' ? roleIds.split(',') : roleIds;
            // 从formData中删除roleIds，因为后端实体中没有这个字段
            delete formData.roleIds;
            
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                
                // 如果选择了角色，保存员工角色关系
                if (roleIdArray && roleIdArray.length > 0) {
                  // 获取员工ID，新增时从返回结果中获取，编辑时从model中获取
                  const employeeId = that.model.id || res.result;
                  that.saveEmployeeRoles(employeeId, roleIdArray);
                } else {
                  that.$emit('ok');
                  that.confirmLoading = false;
                  that.close();
                }
              }else{
                that.$message.warning(res.message);
                that.confirmLoading = false;
              }
            }).catch(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      
      /**
       * 当手机号变更时，自动设置为登录账号
       */
      handlePhoneChange(e) {
        const phone = e.target.value;
        // 仅当添加新员工且登录账号为空或与原手机号相同时自动更新
        if(!this.model.id) {
          const currentUsername = this.form.getFieldValue('username');
          if(!currentUsername || currentUsername === this.model.phone) {
            this.form.setFieldsValue({
              'username': phone
            });
          }
        }
      },
      
      /**
       * 验证登录账号是否唯一
       */
      validateUsername(rule, value, callback) {
        if (!value || value.length === 0) {
          callback();
          return;
        }
        
        // 如果是编辑模式且账号未修改，则不验证唯一性
        if (this.model.id && value === this.model.username) {
          callback();
          return;
        }
        
        const params = {
          username: value
        };
        
        httpAction(this.url.checkUsername, params, 'get').then(res => {
          if (res.success) {
            if (res.result) {
              callback('该手机号已被用作其他员工的登录账号');
            } else {
              callback();
            }
          } else {
            callback();
          }
        }).catch(() => {
          callback();
        });
      },
      
      /**
       * 加载员工的角色信息
       */
      loadEmployeeRoles(employeeId) {
        // 确保employeeId有效
        if (!employeeId) {
          console.error('加载员工角色信息失败：缺少employeeId参数');
          return Promise.resolve([]);
        }
        
        console.log('加载员工角色，employeeId:', employeeId);
        
        // 使用getAction发送GET请求，确保参数正确作为URL查询参数传递
        return getAction('/sys/employee/queryEmployeeRole', { employeeId: employeeId }).then(res => {
          if (res.success && res.result) {
            console.log('获取到角色列表:', res.result);
            return res.result;
          } else {
            console.log('未获取到角色或接口返回失败');
            return [];
          }
        }).catch(err => {
          console.error('获取员工角色信息失败:', err);
          return [];
        });
      },
      
      /**
       * 保存员工角色关系
       */
      saveEmployeeRoles(employeeId, roleIds) {
        const that = this;
        // 确保roleIds是数组
        const roleIdArray = Array.isArray(roleIds) ? roleIds : roleIds.split(',');
        
        // 遍历每个角色，分别保存
        const promises = roleIdArray.map(roleId => {
          return httpAction(that.url.addEmployeeRole, {
            roleId: roleId,
            userIdList: [employeeId]
          }, 'post');
        });
        
        // 等待所有角色保存完成
        Promise.all(promises).then(() => {
          that.$emit('ok');
          that.confirmLoading = false;
          that.close();
        }).catch(err => {
          console.error('保存员工角色关系失败:', err);
          that.$message.warning('保存角色信息失败');
          that.confirmLoading = false;
          that.close();
        });
      }
    }
  }
</script>

<style lang="less" scoped>
/* 优化部门下拉框样式 */
/deep/ .j-depart-tree-select-wrapper {
  width: 100%;
}

/deep/ .ant-select-dropdown {
  max-height: 300px;
  overflow-y: auto;
}

/* 确保日期选择框和下拉框正确显示 */
/deep/ .ant-calendar-picker {
  width: 100%;
}

/deep/ .ant-form-item-control {
  line-height: normal;
}
</style> 